package com.vdongchina.thread.base;

import java.util.concurrent.TimeUnit;

/**
 * 第六课, threadJoin
 * <p>
 * 前驱程序停止才会继续执行
 * 这里先是主线程停止子线程才会执行, 子线程又是等上一个子线程执行完毕才会执行
 */
public class ThreadJoinDemo {

    public static void main(String[] args) throws InterruptedException {

        Thread thread = Thread.currentThread();
        for (int i = 0; i < 10; i++) {
            Thread joinThread = new Thread(new Join(thread), "thread " + i);
            joinThread.start();
            thread = joinThread;
        }
        TimeUnit.SECONDS.sleep(5);
        System.out.println(Thread.currentThread().getName());
    }

    static class Join implements Runnable {
        private Thread thread;

        public Join(Thread thread) {
            this.thread = thread;
        }

        @Override
        public void run() {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "terminate.");
        }
    }


}
